package com.fjwt.gz.mch.web;

import com.fjwt.gz.core.model.security.GzUserDetails;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 日志拦截器
 */
@Slf4j
@Component
public class LoggingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行 GET 方法访问根路径 /
        if (request.getMethod().equalsIgnoreCase("GET") && request.getRequestURI().equals("/")) {
            return true;
        }
        GzUserDetails details = (GzUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断details  原因：未上线之前 前端传参格式错误导致details为空， 临时处理 上线之后删除
        if (ObjectUtils.isEmpty(details)){
            log.error("用户信息为空");
            return true;
        }
        String appId = details.getAppId();
        Long fansId = details.getFansId();
        if (fansId != null) {
            MDC.put("fansId", String.valueOf(fansId));
        }

        if (StringUtils.isNotEmpty(appId)) {
            MDC.put("appId", appId);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理MDC，防止内存泄漏
        MDC.clear();
    }
}
